{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 迭代\n",
    "如果给定一个list或tuple，我们可以通过for循环来遍历这个list或tuple，这种遍历我们称为迭代（Iteration）。\n",
    "\n",
    "在Python中，迭代是通过for ... in来完成的，而很多语言比如C语言，迭代list是通过下标完成的，比如Java代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-1-cdc1124b88da>, line 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-1-cdc1124b88da>\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m    for (i=0; i<list.length; i++) {\u001b[0m\n\u001b[1;37m          ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# Java代码\n",
    "for (i=0; i<list.length; i++) {\n",
    "    n = list[i];\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python中,只要是可迭代对象，无论有无下标，都可以迭代，比如dict就可以迭代："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "d = {'a': 1, 'b': 2, 'c': 3}\n",
    "for key in d:\n",
    "    print(key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 迭代value\n",
    "for value in d.values():\n",
    "    print(value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 同时迭代key和value\n",
    "for k, v in d.items():\n",
    "    print(k, v)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过collections模块的Iterable类型判断\n",
    "from collections import Iterable\n",
    "isinstance('abc', Iterable) # str是否可迭代"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "isinstance([1,2,3], Iterable) # list是否可迭代"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'Iterable' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-2-61b032f1dde0>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0misinstance\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m123\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mIterable\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# 整数是否可迭代\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m: name 'Iterable' is not defined"
     ]
    }
   ],
   "source": [
    "isinstance(123, Iterable) # 整数是否可迭代"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# enumerate函数可以把一个list变成索引-元素对\n",
    "# 可以在for循环中同时迭代索引和元素本身：\n",
    "for i, value in enumerate(['A', 'B', 'C']):\n",
    "    print(i, value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 练习\n",
    "请使用迭代查找一个list中最小和最大值，并返回一个tuple："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def findMinAndMax(L):\n",
    "    if len(L) == 0:\n",
    "        return(None,None)\n",
    "    else:    \n",
    "        min = L[0]\n",
    "        max = L[0]\n",
    "        for x in L:\n",
    "            if x > max:\n",
    "                max = x\n",
    "            if x < min:\n",
    "                min = x        \n",
    "        return(min,max)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "测试成功!\n"
     ]
    }
   ],
   "source": [
    "# 测试\n",
    "if findMinAndMax([]) != (None, None):\n",
    "    print('测试失败!')\n",
    "elif findMinAndMax([7]) != (7, 7):\n",
    "    print('测试失败!')\n",
    "elif findMinAndMax([7, 1]) != (1, 7):\n",
    "    print('测试失败!')\n",
    "elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):\n",
    "    print('测试失败!')\n",
    "else:\n",
    "    print('测试成功!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
